import router from './routers'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { filterAsyncRouter } from '@/store/modules/permission'
import store from '@/store'
import Router from 'vue-router'
import { getToken } from '@/utils/auth' // getToken from cookie

const whiteList = ['/login']// no redirect whitelist

NProgress.configure({ showSpinner: false })// NProgress Configuration

router.beforeEach((to, from, next) => {
    NProgress.start()
    // 已登录且要跳转的页面是登录页
    if (getToken()) {
        console.log('token '+getToken())
        console.log('store.getters.token '+store.getters.token)
        // 已登录且要跳转的页面是登录页
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
                store.dispatch('GetInfo').then(() => { // 拉取user_info
                    // 动态路由，拉取菜单
                    loadMenus(next, to)
                }).catch(() => {
                    store.dispatch('LogOut').then(() => {
                        location.reload() // 为了重新实例化vue-router对象 避免bug
                    })
                })
                // 登录时未拉取 菜单，在此处拉取
            } else if (store.getters.loadMenus) {
                // 修改成false，防止死循环
                store.dispatch('updateLoadMenus')
                loadMenus(next, to)
            } else {
                next()
            }
        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }

})

export const loadMenus = (next, to) => {
    const asyncRouter = filterAsyncRouter(initRouters)
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
        router.addRoutes(asyncRouter) // 动态添加可访问路由表
        next({ ...to, replace: true })
    })
}

const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
    if (onResolve || onReject){
        return originalPush.call(this, location, onResolve, onReject)
    }
    return originalPush.call(this, location).catch(err => err)
}

export const initRouters = [
    {
        'name': '系统管理',
        'path': 'system',
        'hidden': false,
        'redirect': 'noredirect',
        'component': 'Layout',
        'alwaysShow': true,
        'meta': {
            'title': '系统管理',
            'icon': 'system',
            'noCache': true
        },
        'children': [
            {
                'name': 'User',
                'path': 'user',
                'hidden': false,
                'component': 'system/user/index',
                'meta': {
                    'title': '用户管理',
                    'icon': 'peoples',
                    'noCache': true
                }
            },
            {
                'name': 'font',
                'path': 'font',
                'hidden': false,
                'component': 'system/font/index',
                'meta': {
                    'title': '字库管理',
                    'icon': 'peoples',
                    'noCache': true
                }
            }
        ]
    }
]

router.afterEach(() => {
    NProgress.done() // finish progress bar
})



